#include "lfiledialog.h"
#include "ui_lfiledialog.h"

#include <QFileSystemModel>
#include <QItemSelectionModel>
#include <QDebug>
#include <QMessageBox>

LFileDialog::LFileDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LFileDialog)
{
    ui->setupUi(this);

    QIcon icon;
    icon.addFile(tr(":/icon/arrow_up.png"));
    ui->pushButton->setIcon(icon);

    ui->pushButton_select->setEnabled(false);
    connect(ui->pushButton_select, &QPushButton::clicked, [this](){
        auto size = ui->tableView->selectionModel()->selectedRows().size();

        const int max_size = 300;
        if (size > max_size) {
            QString msg = QString("本次选择了[%1]个目录或文件，超过了最大值%2 (若您需要上传大量文件，建议将文件放到一个目录，上传目录即可)。")
                    .arg(size).arg(max_size);
            QMessageBox::warning(this, "选择失败", msg);
        }
        else {
            accept();
        }
    });
    connect(ui->pushButton_cancel, &QPushButton::clicked, this, &LFileDialog::reject);

    m_model = new QFileSystemModel(this);
    ui->tableView->setModel(m_model);

    connect(ui->tableView, &LTableView::sig_rootIndexChanged, [this](const QModelIndex idx){
        if (idx.model()) {
            ui->label_total->setText(QString::number(m_model->rowCount(idx)));
        }
        else {
            ui->label_total->setText(QString::number(QDir::drives().size()));
        }
    });

    connect(m_model, &QFileSystemModel::directoryLoaded, [this](const QString &path){
        ui->label_total->setText(QString::number(m_model->rowCount(m_model->index(path))));
    });

    ui->tableView->adjustSize();

    QPalette pa;
    pa.setColor(QPalette::WindowText,Qt::red);
    ui->label_size->setPalette(pa);

    static QString last_path;
    ui->tableView->setRootIndex(m_model->setRootPath(last_path));
    ui->lineEdit->setText(last_path);

    connect(ui->tableView->selectionModel(), &QItemSelectionModel::selectionChanged, [this](){
        auto size = ui->tableView->selectionModel()->selectedRows().size();
        ui->pushButton_select->setEnabled(size > 0);
        ui->label_size->setText(QString::number(size));
    });

    connect(ui->tableView, &QTableView::doubleClicked, [this](const QModelIndex& index){
        if (m_model->isDir(index)) {
            ui->tableView->selectionModel()->clear();
            auto new_idx = index.sibling(index.row(), 0);
            ui->tableView->setRootIndex(new_idx);

            ui->lineEdit->setText(m_model->filePath(index));
            last_path = m_model->fileInfo(new_idx).absoluteFilePath();
        }
    });
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    auto head_view = ui->tableView->horizontalHeader();
    {
        head_view->setSectionResizeMode(QHeaderView::ResizeToContents);
        head_view->setSectionResizeMode(0, QHeaderView::Stretch);
    }

    ui->tableView->verticalHeader()->hide();
    ui->tableView->setSortingEnabled(true);
    ui->tableView->sortByColumn(0,Qt::AscendingOrder);

    connect(ui->pushButton, &QPushButton::clicked, [this](){
        ui->tableView->selectionModel()->clear();
        auto root_idx = ui->tableView->rootIndex();
        if (!root_idx.model()) {
            return;
        }

        auto par_idx = root_idx.parent();
        ui->tableView->setRootIndex(par_idx);
        last_path = m_model->fileInfo(par_idx).absoluteFilePath();
        ui->lineEdit->setText(last_path);
    });

    Qt::WindowFlags flags=Qt::Dialog;
    flags |=Qt::WindowMaximizeButtonHint;
    // close button will cause fatal error.
    //flags |=Qt::WindowCloseButtonHint;
    setWindowFlags(flags);
}

LFileDialog::~LFileDialog()
{
    delete ui;
}

QString LFileDialog::selectedDir() const
{
    auto ides = ui->tableView->selectionModel()->selectedRows();
    if (ides.empty()) return "";

    auto idx = ides.first().parent();
    if (idx.model() == nullptr) {
        return "";
    }
    auto dir = m_model->fileInfo(idx).absoluteFilePath();
    if (dir.size() > 1 && dir.at(dir.size() - 1) == '/') {
        dir.remove(dir.size()-1, 1);
    }
    return dir;
}

QStringList LFileDialog::selectedItems() const
{
    QStringList items;

    for(auto& idx: ui->tableView->selectionModel()->selectedRows()) {
        if (idx.parent().model()) {
            items << m_model->fileInfo(idx).fileName();
        }
        else {
            items << m_model->fileInfo(idx).absoluteFilePath();
        }
    }

    return items;
}
